package com.smartnsoft.fractory;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * @author Willy Noel
 * @since 2011.06.15
 */
public final class MyProjectGallery
{

  public static final class PageView
      extends LinearLayout
  {

    public PageView(Context context, AttributeSet attrs)
    {
      super(context, attrs);
      setOrientation(LinearLayout.HORIZONTAL);
    }

    public PageView(Context context)
    {
      super(context);
      setOrientation(LinearLayout.HORIZONTAL);
    }

    public void setPagesCount(int count, int dotImageResourceId, int dotSpacing)
    {
      if (count == getChildCount())
      {
        return;
      }
      removeAllViews();
      final Context context = getContext();
      for (int index = 0; index < count; index++)
      {
        final ImageView imageView = new ImageView(context);
        imageView.setSelected(false);
        imageView.setImageResource(dotImageResourceId);
        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = dotSpacing / 2;
        layoutParams.rightMargin = dotSpacing / 2;
        addView(imageView, layoutParams);
      }
    }

    public void setSelection(int position)
    {
      final int actualPosition = position % getChildCount();
      for (int index = 0; index < getChildCount(); index++)
      {
        getChildAt(index).setSelected(index == actualPosition);
      }
    }

  }

  public final static class HardGallery
      extends Gallery
  {

    private boolean disableRequestLayout;

    public HardGallery(Context context, AttributeSet attrs, int defStyle)
    {
      super(context, attrs, defStyle);
    }

    public HardGallery(Context context, AttributeSet attrs)
    {
      super(context, attrs);
    }

    public HardGallery(Context context)
    {
      super(context);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY)
    {
      if (Math.abs(velocityX) < 400)
      {
        return true;
      }
      if (e2.getX() > e1.getX())
      {
        onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
      }
      else
      {
        onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
      }
      return true;
    }

    @Override
    public void requestLayout()
    {
      if (disableRequestLayout == false)
      {
        super.requestLayout();
      }
    }

    public void setDisableRequestLayout(boolean disableRequestLayout)
    {
      this.disableRequestLayout = disableRequestLayout;
    }

  }
}
